package com.ib.applicationservice;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.ib.dataaccess.ITransactionReader;
import com.ib.dataaccess.TransactionReaderFactory;
import com.ib.dto.ProcessingFee;
import com.ib.dto.TransactionAttribute;
import com.ib.service.TransactionProcessingService;

/**
 * API implementation for fetching processing fee calculation report.
 */
public class TransactionReport implements ITransactionReport {

	private static final Logger LOGGER = Logger.getLogger(TransactionReport.class.getName());

	@Override
	public List<ProcessingFee> summaryReport() {

		Map<ProcessingFee, BigDecimal> report = new HashMap<ProcessingFee, BigDecimal>();
		TransactionProcessingService service = new TransactionProcessingService();
		ITransactionReader reader = TransactionReaderFactory.getTransactionReader();
		try {
			List<TransactionAttribute> transactions = reader.readTransaction();
			for (TransactionAttribute aTransaction : transactions) {
				ProcessingFee processingFee = service.processTransaction(aTransaction);
				BigDecimal existingFee = BigDecimal.ZERO;
				if (null != report.get(processingFee)) {
					existingFee = report.get(processingFee);
				}
				BigDecimal newFee = existingFee.add(processingFee.getProcessingFee());
				report.put(processingFee, newFee);
			}
		} catch (Exception e) {
			LOGGER.log(Level.SEVERE, "Exception ocoured while fetching summary.");
		}
		List<ProcessingFee> procesedFeeReport = new ArrayList<ProcessingFee>();
		for (Entry<ProcessingFee, BigDecimal> entry : report.entrySet()) {
			ProcessingFee processingFee = entry.getKey();
			processingFee.setProcessingFee(entry.getValue());
			procesedFeeReport.add(processingFee);
		}
		Collections.sort(procesedFeeReport);
		return procesedFeeReport;
	}
}